<?php

$LOCALPATH = realpath(dirname(__FILE__)); 
include("../include/classes.php");
include("../include/functions.php");
include ("../utils/HttpClient.php");
	$method = $_GET['m'];


	$disp = new Dispatcher();
	$disp->add( "updatemeter" , "dispather_updatemeter" );
	$disp->add( "userlist" , "dispather_userlist" );
	$disp->add( "user" , "dispather_userget" ); 
	$disp->add( "usercheck" , "dispather_usercheck" ); 
	$disp->add( "usersave" , "dispather_usersave" ); 
	$disp->add( "userenable" , "dispather_enableuser" ); 
	
	$disp->add( "userremove" , "dispather_userremove" );
	$disp->add( "userdata" , "dispather_getuserdata" );
	$disp->add( "userdataupload" , "dispather_upload_userdata" );

	$disp->add( "account_passwd" , "dispather_account_passwd" );
	
	$disp->add( "meter" , "dispather_meter" );
	$disp->add( "metersave" , "dispather_metersave" );
	$disp->add( "meterlist" , "dispather_meterlist" );
	$disp->add( "metername" , "dispather_updatemetername" );
	$disp->add( "meterremove" , "dispather_remvoemeter" );
	$disp->add( "meterdata" , "dispather_getmeterdata" );
	$disp->add( "meterdataupload" , "dispather_upload_meterdata" );
	$disp->add( "meterdataremove" , "dispather_removemeterdata" );
	$disp->add( "virmeters" , "dispather_getvirtual_meters" );
	

	$disp->add( "upload_meters" , "dispather_upload_meters" );
	$disp->add( "upload_users" , "dispather_upload_users" );

	$disp->add( "sync" , "dispather_sync" );
	

	$disp->run($method , array());



/**
 * 更新Meter的 USER 属性 ；
 * @return [json string] []
 */
function dispather_sync(){

 	$pageContents = HttpClient::quickGet('http://localhost:10400/sync');	
	//sendSuccessResponse( $pageContents );
	sendResponse(200, $pageContents);
}

/**
 * 更新Meter的 USER 属性 ；
 * @return [json string] []
 */
function dispather_remvoemeter(){

	$meter = $_GET['meter'] ?? null;
	
	if( !$meter )
		throw new Exception("meterId empty");

	$meters = new MeterDao();

	$meters->removeMeter( $meter );

	// 删除 虚拟表计的连接；
 	$mpp = new VirtualDao();
 	$mpp->removeVirtual($meter);
 	$mpp->removeMeter($meter);
	
	sendSuccessResponse( 1 );

}


/**
 * 某虚拟表计的绑定的电表 ；
 * @return [json string] []
 */
function dispather_getvirtual_meters(){

	$vir = $_GET['id'] ?? null;
	
	if( !$vir )
		throw new Exception("id empty");

 
	// 删除 虚拟表计的连接；
 	$mpp = new VirtualDao();
 	;
  	
	sendSuccessResponse($mpp->getMeters($vir) );

}



/**
 * 更新Meter的 USER 属性 ；
 * @return [json string] []
 */
function dispather_updatemeter(){

	$meter = $_GET['meter'] ?? null ;
	$user  = $_GET['user'] ?? null;

	if( !$meter )
		throw new Exception("meterId empty");


	$meters = new MeterDao();

	$meters->update($meter, $user);
	
	sendSuccessResponse( 1 );

} 


/**
 * 更新Meter的 USER 属性 ；
 * @return [json string] []
 */
function dispather_updatemetername(){

	$meter = $_POST['id'] ?? null;
	$name  = $_POST['value'] ?? '';


	if( !$meter )
		throw new Exception("meterId empty");

	$meters = new MeterDao();

	$meters->updateName($meter, $name);
	
	sendSuccessResponse( array(
		"meter" => $meter ,
		"name" => $name 
		) );

} 


/**
 * 更新Meter的  属性 ；
 * @return [json string] []
 */
function dispather_metersave(){

	$meter = $_POST['meter'] ?? null;
	$name  = $_POST['name'] ?? '';
	$type  = $_POST['type'] ?? '';
	$user  = $_POST['user'] ?? '';
	$tags  = $_POST['tags'] ?? '';


	if( !$meter )
		throw new Exception("meterId empty");

	$meters = new MeterDao(); 

	$find = $meters->getMeter($meter);
	if(!$find)
		throw new Exception("Can't find meter by Id :" . $meter);		

	//var_dump($find);

	if( !$type )
		$type = $find['_METERTYPE'];
	if( !$user )
		$user = $find['_USERID'];

	
	//print("type is $type //// ");
	//print("user is $user //// ");


	$meters->update1($meter, $name , $type, $user, $tags) ;
	
	sendSuccessResponse( 1 );

} 


	
/**
 * 得到所有的用户列表
 * @return [type] [description]
 */
function dispather_userlist(){

	$q = $_GET['q'] ?? null;

	$users = new UserDao();
 	
 	
	sendSuccessResponse( $users->getUsers($q) );

}


/**
 * 得到所有的用户列表
 * @return [type] [description]
 */
function dispather_userremove(){

	$user = $_GET['user'] ?? null;
	if( !$user )
		throw new Exception("user empty");

	$meters = new MeterDao();
	$meters->updateMeterByUser($user);

	$users = new UserDao();
 	$users->remove($user);


 	
	sendSuccessResponse( 1 );

}



/**
 * 得到所有的用户列表
 * @return [type] [description]
 */
function dispather_userget(){

	$user = $_GET['user'] ?? null;
	if( !$user )
		throw new Exception("user empty");

 
	$users = new UserDao();
  
 	
	sendSuccessResponse( $users->getUser($user) );

}




/**
 * 得到所有的用户列表
 * @return [type] [description]
 */
function dispather_usercheck(){

	$user = $_GET['user'] ?? null;
	if( !$user )
		throw new Exception("user empty");

 
	$users = new UserDao();
  
  	$find = $users->getUser($user) ;
 	
	sendSuccessResponse( $find ? 1 : 0 );

}



/**
 * ENABLE/DISABLE USER
 * @return [type] [description]
 */
function dispather_enableuser(){
 
 
	$user = $_GET['user'] ?? null;
	if( !$user )
		throw new Exception("user empty");

	$enable = $_GET['enable'] ?? null;
	if( !$enable )
		throw new Exception("enable empty");

	//print("order is $order\n");


 	$users = new UserDao();
	
	$results = $users->enableUser( $user ,$enable  );
 	
	sendSuccessResponse(  $results );

}


/**
 * 得到所有的用户列表
 * @return [type] [description]
 */
function dispather_usersave(){

	$user  = $_POST['user'] ?? null;
	$enable  = $_POST['enable'] ?? 1;
	$name  = $_POST['name'] ?? '';
	$tags  = $_POST['tags'] ?? '';
 	

	if( !$user )
		throw new Exception("user empty");

 
	$users = new UserDao(); 
  	
  	$users->addOrUpdate( $user , $name , $enable , $tags );
 	
	sendSuccessResponse( $users->getUser(1) );

}


/**
 * 得到所有的用户列表
 * @return [type] [description]
 */
function dispather_account_passwd(){

	$uid  = $_POST['uid'] ?? null;
	$passwd  = $_POST['passwd'] ?? null;
	$newpasswd  = $_POST['newpasswd'] ?? null;
	 
 	

	if( !$uid )
		throw new Exception("user empty");
	if( !$passwd )
		throw new Exception("passwd empty");
	if( !$newpasswd )
		throw new Exception("newpasswd empty");

 
	$auth = new AuthDao(); 

	$result = $auth->auth($uid, $passwd);
	if(!$result){
		 sendErrorResponse( -1, 'User "' . $uid .'" auth error');	

	}else {
		$auth->savePasswd( $uid ,$newpasswd);
		sendSuccessResponse(1  );
	}
  	
  	
	

}


/**
 * 得到电表列表
 * @return [type] [description]
 */
function dispather_meterlist(){
 
	$q = $_GET['q'] ?? null ;

	$user = $_GET['user'] ?? null;
	$type = $_GET['type'] ?? null;
	$begin = $_GET['begin'] ?? 0;
	$size = $_GET['size'] ?? 400;

 	$meters = new MeterDao();
	
 	
	sendSuccessResponse( $meters->getMeters( $q , $user , $type , $begin , $size ) );

}



/**
 * 得到电表 
 * @return [type] [description]
 */
function dispather_meter(){
 
	 
	$meter = $_GET['meter'] ?? null;
  	$meters = new MeterDao();
	
 	
	sendSuccessResponse( $meters->getMeter ( $meter ) );

}
/**
 * 查询表计数据；
 * @return [type] [description]
 */
function dispather_getmeterdata(){
 
 
	$meter = $_GET['meter'] ?? null;
	$order = $_GET['order'] ?? '-_ID';
	$begin = $_GET['begin'] ?? 0;
	$size = $_GET['size'] ?? 100;


 	$meters = new MeterDataDao();
	
	$results = $meters->getData( $meter , $order  , $begin , $size );
 	
	sendSuccessResponse(  $results );

}


/**
 * 清除表计数据；
 * @return [type] [description]
 */
function dispather_removemeterdata(){
 
 
	$meter = $_GET['meter'] ?? null;

 	$meters = new MeterDataDao();
	
	$results = $meters->remove( $meter  );
 	
	sendSuccessResponse(  $results );

}


/**
 * 得到用户数据
 * @return [type] [description]
 */
function dispather_getuserdata(){
 
 
	$user = $_GET['user'] ?? null;
	$order = $_GET['order'] ?? '-_ID';
	$date = $_GET['date'] ?? null;
	$begin = $_GET['begin'] ?? 0;
	$size = $_GET['size'] ?? 100;

	//var_dump($_GET);

	//print("order is $order\n");


 	$users = new UserDataDao();
	
	$results = $users->getData( $user ,$date, $order  , $begin , $size );
 	
	sendSuccessResponse(  $results );

}


	    
	$meters = new MeterDao();

	$mpp = new VirtualDao();
 
function dispather_upload_meters_process_sheet($targetFile , $sheet,  $meters , $mpp){
	$values = ExcelUtils::read( $targetFile , array(
	    	"CODE" , "NAME" ,"USER" ,"TAGS" , "VMETER" , "TYPE"
	    	) ,  $sheet );
	    
   	foreach ($values as $row) {
    	$code = trim($row['CODE']);
    	$name = trim($row['NAME']);
    	$user = trim($row['USER']);
    	$virtual = $row['VMETER'] ?? null ;
    	$type = $row['TYPE'] ?? null ; //trim($row['TYPE']);
    	$tags = $row['TAGS'] ?? null ; //trim($row['TAGS']);


   // 	var_dump($row);

    	if($code  ){
    		if(! $name )
    			$name = $code ;

    		if($user=='0' || $user=='#N/A')
    			$user = null;
    		
    		if( !$type )
    			$type = "P" ;

    		//print("code $code , name $name , type $type , user $user tag $tags \n");

    		$meters->addOrUpdate( $code , $name , $type ,  $user , $tags);
    	}

    	// print("$code virtual $virtual \n");

    	if( $mpp && $virtual ) {
    		$vids = explode("," , $virtual);

    		//虚拟电表ID 
    		foreach ($vids as $id ) {
    			
    			$virobj = $meters->getMeter($id);
    			if(!$virobj) {
    				// 新增表计
    			//	print("add new vmeter id $id  \n"); 
    				$virobj = $meters->addOrUpdate( $id , $id , "V" , null , null);	
    			}

				// 删除 虚拟表计的连接；
			 	$mpp->removeMeter( $code );
			 	// 保存新的表计连接；
			 	$mpp->save($code , $id );
    		}
    	}

    }	
}


/**
 * 上传文件 表计定义文件
 * @return [type] [description]
 */
function dispather_upload_meters(){
 	
 	$fileName = $_FILES ['file'] ['name'];
	if (!empty ( $fileName ))
	{
	    $tmp_file = $_FILES ['file'] ['tmp_name'];

	    // print("tmpfile " . $tmp_file);

	    $fileTypes = explode ( ".", $fileName );
	    $fileType = $fileTypes [count ( $fileTypes ) - 1];
	    
	    /*判别是不是.xls文件，判别是不是excel文件*/
	    if (strtolower ( $fileType) != "xls" && strtolower ( $fileType) != "xlsx" )              
	    {
	        throw new Exception('不是Excel文件，重新上传' );
	    }

	    /*设置上传路径*/
	    $savePath = SITE_PATH . '/upfile';
	    /*以时间来命名上传的文件*/
	    $str = date ( 'Ymdhis' ); 
	    $file_name = $str . "." . $fileType;
	    $targetFile = $savePath . $file_name;
	    /*是否上传成功*/
	    if (! copy ( $tmp_file, $targetFile )) 
	    {
	        throw new Exception( '上传失败' );   
	    }


		$meters = new MeterDao();

		$mpp = new VirtualDao();


		dispather_upload_meters_process_sheet( $targetFile , "METERS" , $meters , $mpp);
	 	dispather_upload_meters_process_sheet( $targetFile , "VMETERS" , $meters , null );

	    unlink($targetFile);
	    
	    sendSuccessResponse( 1 ); 
	}
}



/**
 * 上传文件
 * @return [type] [description]
 */
function dispather_upload_users(){
 	
 	$fileName = $_FILES ['file'] ['name'];
	if (!empty ( $fileName ))
	{
	    $tmp_file = $_FILES ['file'] ['tmp_name'];

	    // print("tmpfile " . $tmp_file);

	    $fileTypes = explode ( ".", $fileName );
	    $fileType = $fileTypes [count ( $fileTypes ) - 1];
	    
	    /*判别是不是.xls文件，判别是不是excel文件*/
	    if (strtolower ( $fileType) != "xls" && strtolower ( $fileType) != "xlsx" )              
	    {
	        throw new Exception('不是Excel文件，重新上传' );
	    }

	    /*设置上传路径*/
	    $savePath = SITE_PATH . '/upfile';
	    /*以时间来命名上传的文件*/
	    $str = date ( 'Ymdhis' ); 
	    $file_name = $str . "." . $fileType;
	    $targetFile = $savePath . $file_name;
	    /*是否上传成功*/
	    if (! copy ( $tmp_file, $targetFile )) 
	    {
	        throw new Exception( '上传失败' );   
	    }

	    $values = ExcelUtils::read( $targetFile , array(
	    	"CODE" , "NAME" , "TAGS" , "STATUS"
	    	) , "USERS");


	    unlink($targetFile);

		$users = new UserDao();


	    foreach ($values as $row) {
	    	$code = trim($row['CODE']);
	    	$name = trim($row['NAME']);
	    	$tags = trim($row['TAGS']);
			$status = $row['STATUS'] ?? null ;  
			
	    //	var_dump($row);
	    //	print("code $code , name $name <br/>\n");
	    	if( $code  ){
	    		if(!$name )
	    			$name = $code ;
				if($status){
					// 
					$status = trim($status);
					if($status == 'REMOVED') {
						$users->remove($code);
						continue;
					}
				}
				
	    		
	    		$users->addOrUpdate( $code , $name , 1, $tags);
	    	}

	    }
	    
	    sendSuccessResponse( 1 ); 
	}
}





/**
 * 上传文件 表计定义数据文件
 * @return [type] [description]
 */
function dispather_upload_meterdata(){
 	
 	$fileName = $_FILES ['file'] ['name'];
	if (!empty ( $fileName ))
	{
	    $tmp_file = $_FILES ['file'] ['tmp_name'];

	    // print("tmpfile " . $tmp_file);

	    $fileTypes = explode ( ".", $fileName );
	    $fileType = $fileTypes [count ( $fileTypes ) - 1];
	    
	    /*判别是不是.xls文件，判别是不是excel文件*/
	    if (strtolower ( $fileType) != "xls" && strtolower ( $fileType) != "xlsx" )              
	    {
	        throw new Exception('不是Excel文件，重新上传' );
	    }

	    /*设置上传路径*/
	    $savePath = SITE_PATH . '/upfile';
	    /*以时间来命名上传的文件*/
	    $str = date ( 'Ymdhis' ); 
	    $file_name = $str . "." . $fileType;
	    $targetFile = $savePath . $file_name;
	    /*是否上传成功*/
	    if (! copy ( $tmp_file, $targetFile )) 
	    {
	        throw new Exception( '上传失败' );   
	    }

	    $values = ExcelUtils::read( $targetFile , array(
	    	"CODE" , "TIME" ,"VALUE"
	    	));
	    unlink($targetFile);
	    
		$meters = new MeterDataDao();


	    foreach ($values as $row) {
	    	$code = $row['CODE'];
	    	$time = $row['TIME'];
	    	$value = $row['VALUE'];
	    	if($code  ){
	    		// 2015-02-01 03:00:08
	    		$time = DateTime::createFromFormat('Y-m-d H:i:s',$time );

	    		$meters->insert( $code , $time , floatval( $value) );
	    	}
	    	 

	    }
	    
	    sendSuccessResponse(1); 
	}
}



/**
 * 上传文件 用户数据文件
 * @return [type] [description]
 */
function dispather_upload_userdata(){
 	
 	$fileName = $_FILES ['file'] ['name'];
	if (!empty ( $fileName ))
	{
	    $tmp_file = $_FILES ['file'] ['tmp_name'];

	    // print("tmpfile " . $tmp_file);

	    $fileTypes = explode ( ".", $fileName );
	    $fileType = $fileTypes [count ( $fileTypes ) - 1];
	    
	    /*判别是不是.xls文件，判别是不是excel文件*/
	    if (strtolower ( $fileType) != "xls" && strtolower ( $fileType) != "xlsx" )              
	    {
	        throw new Exception('不是Excel文件，重新上传' );
	    }

	    /*设置上传路径*/
	    $savePath = SITE_PATH . '/upfile';
	    /*以时间来命名上传的文件*/
	    $str = date ( 'Ymdhis' ); 
	    $file_name = $str . "." . $fileType;
	    $targetFile = $savePath . $file_name;
	    /*是否上传成功*/
	    if (! copy ( $tmp_file, $targetFile )) 
	    {
	        throw new Exception( '上传失败' );   
	    }

	    $values = ExcelUtils::read( $targetFile , array(
	    	"CODE" , "DATE", "TIME" ,"VALUE"
	    	));
	    unlink($targetFile);
	    
		$meters = new UserDataDao();


	    foreach ($values as $row) {
	    	$code = $row['CODE'];
	    	$date = $row['DATE'];
	    	$time = $row['TIME'];
	    	$value = $row['VALUE'];
	    	$code = trim($code);
	    	if( $code!=null && $code!='' ){
	    		// 2015-02-01 03:00:08
	    		$time = trim($time);
	    		$date =  trim($date);
	    		 
	    		$time1 = parseTime( $date , $time); 

	    		$meters->insert( $code , $date , $time1 , floatval( $value) );
	    	}
	    	 

	    }
	    
	    sendSuccessResponse(1); 
	}
}


function parseTime( $type , $time1 ){
	$time1 = trim($time1);
	$type =  trim($type);
	if( $type == "M"){
		$time = DateTime::createFromFormat('Y-m',$time1 );
		if($time){
			$year =  $time->format("Y");
			$month = $time->format("m");
			$time->setTime(0,0,0);
			$time->setDate( $year, $month, 1);
		}
	}
	else if( $type == "D"){
		$time = DateTime::createFromFormat('Y-m-d',$time1 );
		if($time){
			 
			$time->setTime(0,0,0);
			 
		}
	}
	else if( $type == "Y"){
		$time = DateTime::createFromFormat('Y',$time1 ); 
		if($time){
			$year =  $time->format("Y");
			 
			$time->setTime(0,0,0);
			$time->setDate( $year, 1 , 1);
		}
	}
	else 
		$time = DateTime::createFromFormat('Y-m-d H:i:s',$time1 );

	if($time == null)
		throw new Exception("Inviald time format "  . $time1 . " $type" );

	return $time;
}



?>
